﻿// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="MyProfileController.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.CommonLayer;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.DomainLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Layers.SecurityLayer.Models.MetaModels;
using InnovaApp.Portals.MVC4Portal.Models.JSonModels;
using InnovaApp.Portals.MVC4Portal.Models.MetaModels.ContactManagement;
using InnovaApp.Portals.MVC4Portal.Models.ViewModels;
using InnovaApp.Portals.MVC4Portal.Models.ViewModels.LayoutViewModels;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.Extensions;
using INNOVACALL.Framework.Common.InnovacallExceptions;
using INNOVACALL.Framework.Common.MVCHelpers;
using INNOVACALL.Framework.Common.MVCHelpers.Localization;
using System.Drawing;
using System.Drawing.Imaging;
using InnovaApp.Portals.MVC4Portal.Filters;
using INNOVACALL.Framework.Common.Models;

namespace InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers
{
    /// <summary>
    /// Class MyProfileController
    /// </summary>
    public partial class MyProfileController : _ViewControllers_Base<MyProfile_ViewModel>
    {
        /// <summary>
        /// Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Portals.InnovaAppFrontOfficePortal.Controllers.MyProfileController";
            base.Initialize(requestContext);
        }

        /// <summary>
        /// Gets the current user profile.
        /// </summary>
        /// <param name="language">The language.</param>
        /// <param name="ajaxModel">The ajax model.</param>
        /// <returns>JsonResult.</returns>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.IdentificationException">
        /// </exception>
        /// <exception cref="INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException"></exception>
        [HttpPost, Authorize, CacheManager(enCacheMode.NoCache)]
        public JsonResult GetCurrentUserProfile(string language, MyProfileFeed_JSonModel ajaxModel)
        {
            string eMethod = eMethodBase + "GetCurrentUserProfile[Post]";
            string scriptToExecute = string.Empty;
            object eParameters = null;
            INNOVACALL.Framework.Common.MVCHelpers.Localization.CommonLocalization.SetCurrentThreadLanguage(language);
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            try
            {
                using (DataRepositories _dataContext = new DataRepositories())
                {
                    var CurrentUser = Membership.GetUser();
                    if (CurrentUser == null)
                    {
                        throw new INNOVACALL.Framework.Common.InnovacallExceptions.IdentificationException(eMethod, eParameters, Resources.View_MyProfile_ErrMsg_CurrentUserNotFound);
                    }
                    Guid currentUserId = (Guid)CurrentUser.ProviderUserKey;
                    InnoAppUser dbCurrentUser = _dataContext.InnoAppUser_Rep.GetById(currentUserId);
                    if (dbCurrentUser == null)
                    {
                        throw new INNOVACALL.Framework.Common.InnovacallExceptions.IdentificationException(eMethod, eParameters, Resources.View_MyProfile_ErrMsg_CurrentUserNotFoundInDatabase);
                    }
                    MyProfile_ViewModel modelToFeed = new MyProfile_ViewModel();

                    #region Identity
                    Contact dbContact = _dataContext.Contact_Rep.Query(x => (Guid)x.FK_InnoAppUser == currentUserId).FirstOrDefault();
                    if (dbContact == null)
                    {
                        throw new INNOVACALL.Framework.Common.InnovacallExceptions.DataIntegrityException(eMethod, eParameters, Resources.View_MyProfile_ErrMsg_CurrentUserContactNull);
                    }
                    else
                    {
                        modelToFeed.Contact = ObjectMapperManager.DefaultInstance.GetMapper<Contact, ManagedContact_MetaModel>().Map(dbContact);
                    }
                    IEnumerable<Genre> dbGenres = _dataContext.Genre_Rep.GetAll().AsEnumerable();
                    List<SelectListItem> Genres = dbGenres.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = CommonLocalization.LookupResource(typeof(Resources), x.Name), Selected = false }).ToList();
                    Genres.Insert(0, new SelectListItem() { Value = "-1", Text = string.Empty, Selected = Genres.Select(x => x.Selected).Count() == 0 });
                    modelToFeed.Contact.Genres = Genres;

                    modelToFeed.Contact.AvailableTelecomTypes = _dataContext.TelecomType_Rep.GetAll().OrderBy(x => x.Name).Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Selected = false }).ToList();
                    modelToFeed.Contact.AvailableTelecomTypes.Insert(0, new SelectListItem() { Value = "-1" });

                    modelToFeed.Contact.AvailableCompetencies = _dataContext.Competency_Rep.GetAll().OrderBy(x => x.Name).Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Selected = false }).ToList();
                    modelToFeed.Contact.AvailableCompetencies.Insert(0, new SelectListItem() { Value = "-1" });

                    if (string.IsNullOrEmpty(dbContact.IconPath))
                    {
                        modelToFeed.Contact.IconPath = PortalEnvironment.UserEmptyIconPath;
                    }
                    else
                    {
                        modelToFeed.Contact.IconAlt = string.Format("{0} {1}", dbContact.FirstName, dbContact.LastName);
                        modelToFeed.Contact.IconPath = dbContact.IconPath;
                    }

                    IEnumerable<Language> dbLanguages = _dataContext.Language_Rep.GetAll().OrderBy(x => x.SortIndex).AsEnumerable();
                    List<SelectListItem> Languages = dbLanguages.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = CommonLocalization.LookupResource(typeof(Resources), string.Format("View_All_Languages_{0}", x.Name)), Selected = modelToFeed.Contact.FK_Language == x.Id }).ToList();
                    modelToFeed.Contact.Languages = Languages;
                    #endregion

                    #region Password

                    #endregion

                    #region Addresses
                    List<Contact_ContactAddress> dbContact_ContactAddresses = _dataContext.Contact_ContactAddress_Rep.Query(x => x.FK_Contact == dbContact.Id).ToList();
                    List<Contact_ContactAddress_MetaModel> Contact_ContactAddresses = new List<Contact_ContactAddress_MetaModel>();
                    foreach (var dbContact_contactAddress in dbContact_ContactAddresses)
                    {
                        var contact_ContactAddressToAdd = ObjectMapperManager.DefaultInstance.GetMapper<Contact_ContactAddress, Contact_ContactAddress_MetaModel>().Map(dbContact_contactAddress);
                        contact_ContactAddressToAdd.IsDeliveryAddress = dbContact_contactAddress.Contact_ContactAddress_AddressType.Where(x => x.AddressType.isDelivery.HasValue && x.AddressType.isDelivery.Value).Count() > 0;
                        contact_ContactAddressToAdd.IsInvoicingAddress = dbContact_contactAddress.Contact_ContactAddress_AddressType.Where(x => x.AddressType.isBilling.HasValue && x.AddressType.isBilling.Value).Count() > 0;
                        contact_ContactAddressToAdd.IsPostAddress = dbContact_contactAddress.Contact_ContactAddress_AddressType.Where(x => x.AddressType.isCorrespondence.HasValue && x.AddressType.isCorrespondence.Value).Count() > 0;
                        Contact_ContactAddresses.Add(contact_ContactAddressToAdd);
                    }
                    if (Contact_ContactAddresses.Count == 0)
                    {
                        Contact_ContactAddresses.Add(new Contact_ContactAddress_MetaModel() { Id = -1 });
                    }
                    modelToFeed.Contact.Contact_ContactAddresses = Contact_ContactAddresses;
                    #endregion

                    #region Telecoms
                    List<Contact_TelecomType> dbContact_TelecomTypes = _dataContext.Contact_TelecomType_Rep.Query(x => x.FK_Contact == dbContact.Id).ToList();
                    List<Contact_TelecomType_MetaModel> Contact_TelecomTypes = ObjectMapperManager.DefaultInstance.GetMapper<List<Contact_TelecomType>, List<Contact_TelecomType_MetaModel>>().Map(dbContact_TelecomTypes);
                    if (Contact_TelecomTypes.Count == 0)
                    {
                        Contact_TelecomTypes.Add(new Contact_TelecomType_MetaModel() { Id = -1 });
                    }
                    modelToFeed.Contact.Contact_TelecomTypes = Contact_TelecomTypes;
                    #endregion

                    #region Competencies
                    List<Contact_Competency> dbContact_Competencies = _dataContext.Contact_Competency_Rep.Query(x => x.FK_Contact == dbContact.Id).ToList();
                    List<Contact_Competency_MetaModel> Contact_Competencies = ObjectMapperManager.DefaultInstance.GetMapper<List<Contact_Competency>, List<Contact_Competency_MetaModel>>().Map(dbContact_Competencies);
                    if (Contact_Competencies.Count == 0)
                    {
                        Contact_Competencies.Add(new Contact_Competency_MetaModel() { Id = -1 });
                    }
                    #endregion

                    string htmlContent = base.RenderPartialViewToString("_MyProfile", modelToFeed);
                    toReturn.Data = new INNOVACALLAjaxResponse(
                        success: true,
                        domElementToUpdate: ajaxModel.HtmlElementToUpdate,
                        htmlContent: htmlContent,
                        scriptToExecute: null,
                        messageTitle: null,
                        message: null,
                        additionalData: new { @modelToFeed = modelToFeed, @forUserId = currentUserId }
                    );
                }
            }
            catch (Exception ex)
            {
                INNOVACALL.Framework.Common.InnovacallExceptions.CommonException iex = new INNOVACALL.Framework.Common.InnovacallExceptions.CommonException(eMethod, eParameters, ex.Message);
                iex.LogIt();
                toReturn.Data = new INNOVACALLAjaxResponse(
                    success: false,
                    domElementToUpdate: null,
                    htmlContent: null,
                    scriptToExecute: "$.fn.jqDialogAlert(a.messageTitle ,a.message,'');",
                    messageTitle: Resources.View_All_DialogErrorTitle,
                    message: ex.LayoutException(),
                    additionalData: null
                );
            }
            return toReturn;
        }

    }
}
